package red.stu.mc.api.http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

public final class HttpsRequest {
	
	public static final String REQUEST_METHOD_GET = "GET";
	public static final String REQUEST_METHOD_POST = "POST";
	public static final String DEFAULT_CHARSET = "UTF-8";
	
	public static String sendGet(String url, String param) {
		return sendGet(url, param, DEFAULT_CHARSET);
	}
	
	public static String sendGet(String url, String param, String charset) {
		return httpsRequest(url, REQUEST_METHOD_GET, param, charset);
	}
	
	public static String sendPost(String url, String param) {
		return sendPost(url, param, DEFAULT_CHARSET);
	}
	
	public static String sendPost(String url, String param, String charset) {
		return httpsRequest(url, REQUEST_METHOD_POST, param, charset);
	}

	/**
	 * 发送httpsGET/POST请求
	 * @param requestUrl
	 * @param requestMethod GET / POST
	 * @param outputStr 参数字符串
	 * @param charset 字符编码
	 * @return
	 */
	public static String httpsRequest(String requestUrl, String requestMethod,
			String outputStr, String charset) {
		StringBuffer buffer = null;
		try {
			// 创建SSLContext
			SSLContext sslContext = SSLContext.getInstance("SSL");
			TrustManager[] tm = { new HttpsX509TrustManager() };
			// 初始化
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 获取SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.addRequestProperty("", "");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(requestMethod);
			conn.setHostnameVerifier(new HttpsRequest().new TrustAnyHostnameVerifier());
			// 设置当前实例使用的SSLSoctetFactory
			conn.setSSLSocketFactory(ssf);
			conn.connect();
			// 往服务器端写内容
			if (null != outputStr) {
				OutputStream os = conn.getOutputStream();
				os.write(outputStr.getBytes(charset));
				os.close();
			}

			// 读取服务器端返回的内容
			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, charset);
			BufferedReader br = new BufferedReader(isr);
			buffer = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				buffer.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer == null ? null : buffer.toString();
	}
	
	public final class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			// 直接返回true
			return true;
		}
	}
}
